package com.freen.fadmin.config.authenticationhandler.jwt.sysuser;

import com.freen.fadmin.entity.sys.SysuserLoginLog;
import com.freen.fadmin.repository.sys.SysuserLoginLogRepository;
import com.freen.fadmin.util.IpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component("jwtSysuserAuthenticationFailureHandler")
public class JwtSysuserAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
    @Autowired
    private SysuserLoginLogRepository sysuserLoginLogRepository;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        request.setCharacterEncoding("UTF-8");
        String sysusername = request.getParameter("username");
        SysuserLoginLog sysuserLoginLog = new SysuserLoginLog();
        sysuserLoginLog.setLoginip(IpUtils.getIpAddr(request));
        sysuserLoginLog.setLogintime(System.currentTimeMillis());
        sysuserLoginLog.setSysusername(sysusername);
        sysuserLoginLog.setStates(0);
        sysuserLoginLog.setWay(2);
        sysuserLoginLogRepository.save(sysuserLoginLog);

        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.write("{\"status\":\"error\",\"message\":\"用户名或密码错误\"}");
        out.flush();
        out.close();
    }
}
